package com.mk.legoscans2.data;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class LocalStorageThumbnailService implements ThumbnailService {

	private Context _context;
	private ThumbnailService _inner;
	
	public LocalStorageThumbnailService(Context context, ThumbnailService inner)
	{
		_context = context;
		_inner = inner;
	}
	
	public Bitmap getThumbnail(String scanId) {
		String fileName = getFileName(scanId);
		
		Bitmap bmp;
		try {
			FileInputStream fis = _context.openFileInput(fileName);
			bmp = BitmapFactory.decodeStream(fis);
			fis.close();
		} catch (FileNotFoundException e) {
			bmp = _inner.getThumbnail(scanId);
			if(bmp == null)
				return null;
			storeThumbnail(bmp, scanId);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		return bmp;
	}

	private String getFileName(String scanId) {
		return "thumbnail_" + scanId + ".png";
	}

	private void storeThumbnail(Bitmap bmp, String scanId) {
		try {
			FileOutputStream fos = _context.openFileOutput(getFileName(scanId), Context.MODE_PRIVATE);
		    bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
		    fos.close();
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
